package com.logic.landseaserver.service.callback;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logic.common.security.SecurityUtils;
import com.logic.landseaserver.common.LandeaConstants.AccountStatus;
import com.logic.landseaserver.common.LandeaConstants.QueryUesdCodeType;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.enums.BillStatusEnum;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.util.ConstantChar;
import com.logic.landseaserver.domain.BillDetail;
import com.logic.landseaserver.domain.MonthlyBill;
import com.logic.landseaserver.domain.PreOffrentBill;
import com.logic.landseaserver.models.authcode.service.AuthCodeService;
import com.logic.landseaserver.models.independent.service.BillIndependentService;
import com.logic.landseaserver.models.payment.service.PaymentService;
import com.logic.landseaserver.models.prepayment.service.PrepaymentService;
import com.logic.landseaserver.persistence.read.BillDetailReadMapper;
import com.logic.landseaserver.persistence.read.BillReadMapper;
import com.logic.landseaserver.persistence.read.PreOffrentBillReadMapper;
import com.logic.landseaserver.persistence.write.MonthlyBillWriteMapper;
import com.logic.landseaserver.service.IDdLockService;
import com.logic.landseaserver.ws.dto.BillDTO;

/**
 *
 * 项目名称：system-server</br>
 * 类名称：MonthBillBusinessService</br>
 * 类描述：月账单回调业务逻辑处理</br>
 * 创建人：Tony</br>
 * 创建时间：2017年7月5日 下午4:05:47</br>
 * 
 * @version 1.0
 *
 */
@Service("WebankCallBack_BT2")
public class MonthBillBusinessService implements IWebankCallbackHandler
{
    private static final Logger LOG = LoggerFactory.getLogger(MonthBillBusinessService.class);
    
    @Autowired
    private PaymentService paymentService;
    
    @Autowired
    private BillReadMapper billReadMapper;
    
    @Autowired
    private BillDetailReadMapper billDetailReadMapper;
    
    @Autowired
    private MonthlyBillWriteMapper monthlyBillWriteMapper;
    
    @Autowired
    private IDdLockService ddLockService;
    
    @Autowired
    private BillIndependentService billIndependentService;
    
    @Autowired
    private AuthCodeService authCodeService;
    
    @Autowired
    private PreOffrentBillReadMapper preOffrentBillReadMapper;
    
    @Autowired
    private PrepaymentService prepaymentService;
    
    @Override
    public Object process(HashMap<String, Object> param)
        throws LandseaException
    {
        LOG.info("月账单业务处理start");
        Integer billId = (Integer)param.get("billId");
        Date payTime = (Date)param.get("payTime");
        try
        {
            BillDTO bdto = billReadMapper.selectByPrimaryKey(billId);
            Integer contractId = bdto.getContractId();
            String billMonth = bdto.getBillMonth();
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            Date month = sdf.parse(billMonth);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(month);
            calendar.add(Calendar.MONTH, -1);
            String lastBillMonth = sdf.format(calendar.getTime());
            
            Double currentPayMoney = (Double)param.get("currentPayMoney");
            BillDTO bill = paymentService.updateBillStateAndMoney(billId, currentPayMoney);
            boolean result = this.checkMonthBillAndBill(billId, contractId, lastBillMonth);
            if (result)
            {
                // 如果支付成功
                if (BillStatusEnum.BIST2.getCode().equals(bill.getBillStatus()))
                {
                    // ADD by Junny 退房账单特殊处理 将往期所有其他费项都改为已支付
                    if (ConstantChar.BILLING_OF_OFFRENT_BILL.equals(bill.getName()))
                    {
                        MonthlyBill monthlyBill = new MonthlyBill();
                        monthlyBill.setBillNo(bdto.getBillNo());
                        monthlyBill.setContractId(contractId);
                        monthlyBill.setStatus(BillStatusEnum.BIST2.getCode());
                        monthlyBill.setLastModifiedBy(SecurityUtils.getCurrentLogin().getUserId());
                        monthlyBillWriteMapper.updateMonthlyBillByOffBill(monthlyBill);
                        // 微众和pos处理月结往BalanceSheet里面修改数据
                        billIndependentService.monUpdateBalanceSheetRent(contractId, payTime);
                        
                        // 退租结束，更新账户为正常
                        prepaymentService.updateAccountStatusByContract(contractId, AccountStatus.NORMAL);
                        LOG.info("退租账单支付完毕,已更新账户contractId=" + contractId + "的账户状态为：正常.");
                    }
                    else
                    {
                        MonthlyBill monthlyBill = new MonthlyBill();
                        monthlyBill.setBillMonth(lastBillMonth);
                        monthlyBill.setBillNo(bdto.getBillNo());
                        monthlyBill.setContractId(contractId);
                        monthlyBillWriteMapper.updateMonthlyBillStatusAndBillNo(monthlyBill);
                        // 微众和pos处理月结往BalanceSheet里面修改数据
                        billIndependentService.monUpdateBalanceSheet(billId, payTime);
                    }
                    
                    // 查询是否有房租,不考虑授权码记录
                    BillDetail billDetail = billDetailReadMapper.checkIsContainRent(billId);
                    if (null != billDetail)
                    {
                        // 如果有房租，则要重置密码有效期为房租截止日期,不需要发送短信
                        ddLockService.resetPasswordEffectiveTime(null, contractId, null);
                    }
                }
                
                // 更新授权码为已使用状态
                // 先查询是否是退房账单
                PreOffrentBill preOffrentBill = preOffrentBillReadMapper.queryByContractId(contractId);
                if (null != preOffrentBill)
                {
                    // 退房账单时，mainId为退房结算单的ID
                    authCodeService.updateCouponStatusAfterPay(QueryUesdCodeType.OFFRENT, preOffrentBill.getId());
                }
                else
                {
                    // 月结账单时，mainId为BillId
                    authCodeService.updateCouponStatusAfterPay(QueryUesdCodeType.MONTHBILL, billId);
                }
            }
            else
            {
                LOG.error(LandseaErrorMessageEnum.BILL_DETAIL_NOT_MATCH_MONTHLY_BILL.getDesc());
            }
        }
        catch (Exception e)
        {
            LOG.error("WebankCallBack_BT2 |handle callback event failed.", e);
            throw LandseaException.createException(LandseaErrorMessageEnum.WEBANK_CALLBACK_BT2_PARAM_ERROR, e);
        }
        LOG.info("月账单业务处理end");
        return null;
    }
    
    private boolean checkMonthBillAndBill(Integer billId, Integer contractId, String billMonth)
    {
        /*
         * List<BillDetail> billdetaillist = billDetailReadMapper.getBillDetailFee(billId); List<MonthlyBill>
         * MonthlyBillList = monthlyBillReadMapper.selectForBill(contractId, billMonth); return
         * billdetaillist.size()==MonthlyBillList.size();
         */
        // TOOD delete by junny 不再check
        return true;
    }
    
}
